<?php
/*
Plugin Name: 划词评论
Plugin URI: http://www.lzyy.name/blog/archives/31
Description: 选中一段文字，然后对这段文字评论
Version: 1.0
Author: lzyy
Author URI: http://www.lzyy.name/blog
*/

function db_install () {
    global $wpdb;

    $table_name = $wpdb->prefix . "comments_sigma";
        $sql = 'CREATE TABLE '.$table_name.' (
            comment_post_ID INT(10) NOT NULL,
            comment_id INT(10) NOT NULL,
            sigma VARCHAR(20) NOT NULL,
            KEY (comment_post_ID)
        );';
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);

}

function get_text_comment()
{
    global $wpdb;
    global $post;
    $sql = 'SELECT * FROM '.$wpdb->prefix ."comments_sigma
           WHERE `comment_post_ID` = ".$post->ID;
    $rs = $wpdb->get_results($sql);
    //print_r($rs[0]->comment_post_ID);
    return $rs;
}

function add_sigma($comment_id)
{
    global $wpdb;

    $sigma = $_COOKIE['sigma'];
    $postID = (int)$_COOKIE['postID'];
    $sigmaArr = explode(',',$sigma);
    if(count($sigmaArr)==2):
    $sql = 'INSERT INTO '.$wpdb->prefix.'comments_sigma(
            `comment_post_ID`,`comment_id`,`sigma`)
            VALUES("'.$postID.'","'.$comment_id.'","'.$sigma.'")';
    if($wpdb->query($sql))
    {
        return '1';
    }
    else
    {
        return $sql;
    }
    endif;
}

function add_jquery()
{
    echo <<<EOT
    <script type='text/javascript'>
        if(typeof(jQuery)=='undefined')
        {
            document.write('<scri'+'pt src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" type="text/javascript"></scri'+'pt>');
        }
    </script>
    <style>
    .highlight{background:#FAF7B2;cursor:pointer}
    #cmtform p{text-align:left}
    #float-cmt p.cmt-info{text-align:right;color:#666;padding-bottom:5px}
    #float-cmt{background:#f8f8f8;border:1px solid #aaa;padding:10px}
    #float-cmt li{list-style:none;padding:10px}
    #closeopenselctcmt{float:right;cursor:pointer;background:yellow}
    </style>
EOT;
}

function add_text_comment()
{
if(strstr($_SERVER['HTTP_USER_AGENT'],'Gecko')<0)
{
    return;
}

global $comment;
global $user_ID;
global $post;


global $user_identity;
$rs = get_text_comment();
$sigma = '[';//存储选择文字的起点和终点
$text_comments = '[';//存储评论id
foreach($rs as $cmt)
{
    $sigma .= "'".$cmt->sigma."'".',';
    $text_comments .= "'".$cmt->comment_id."'".',';
}
$sigma = rtrim($sigma,',');
$sigma .=']';
$text_comments = rtrim($text_comments,',');
$text_comments .= ']';

$siteurl = get_option('siteurl');
$logouturl = wp_logout_url(get_permalink());
$postID = $post->ID;
echo <<<EOT
<div style="position:absolute;display:none;width:450px" id='float-cmt'>

    <form action="$siteurl/wp-comments-post.php" method="post" id="cmtform" name='cmtform'>
EOT;
    if ( $user_ID ):
echo <<<EOT
    <p>欢迎<a href="$siteurl/wp-admin/profile.php">$user_identity</a>来说两句 | <a href="$logouturl" title="退出登录">退出</a></p>
EOT;
    else:
echo <<<EOT
    <p><input type="text" name="author" value="$comment_author" size="22" tabindex="8" aria-required='true' />

    <label for="author"><small>Name (必填)</small></label></p>



    <p><input type="text" name="email" value="$comment_author_email" size="22" tabindex="9" aria-required='true' />

    <label for="email"><small>Mail (不会公开) (必填)</small></label></p>



    <p><input type="text" name="url" value="$comment_author_url" size="22" tabindex="10" />

    <label for="url"><small>网站</small></label></p>
EOT;
    endif;

echo <<<EOT
    <p><textarea name="comment" cols="40" rows="10" tabindex="11" style="width:444px"></textarea></p>
    <p><input type="submit" tabindex="12" value="发表评论" class='btn'/>
EOT;
    comment_id_fields();
echo <<<EOT
    </p>
EOT;
    do_action('comment_form', $post->ID);
echo <<<EOT
    </form>
</div>

<SCRIPT LANGUAGE="JavaScript">
    var currentSigma='';
    sigma = eval($sigma);
    hiddenCmts = eval($text_comments);
    var articleId = 'article';

    hideCmts();
    selectHighLight = false;//是否选择了文本区域


    function hideCmts()
    {
        for(var i=0;i<hiddenCmts.length;i++)
        {
            $("#comment-"+hiddenCmts[i]).attr('sig',sigma[i]);
            //$("#comment-"+hiddenCmts[i]).hide();
        }
    }



    function init()
    {
        is_ie = document.all;
        cmt = getObj('float-cmt');
        addListeners();
    }

    function addListeners()
    {
        if(document.addEventListener)
        {
            //document.addEventListener("dblclick", _dictQuery, true);
            getObj(articleId).addEventListener("mouseup", showCmt, true);
            getObj(articleId).addEventListener("mousedown", mouseHideCmt, true);
            //$("body").get(0).addEventListener("mousedown", mouseHideCmt, true);
            document.addEventListener("keydown",keyHideCmt, true);
        }
        else if (document.attachEvent)
        {
            //document.attachEvent("ondblclick", _dictQuery);
            getObj(articleId).attachEvent("onmouseup", showCmt);
            getObj(articleId).attachEvent("onmousedown", mouseHideCmt);
            document.attachEvent("onkeydown", keyHideCmt);
        }

    }

    $("#closeopenselctcmt").click(function(){
        if($(this).text().indexOf('关闭')>=0){
			if(!is_ie) getObj(articleId).removeEventListener("mouseup", showCmt, true);
			else getObj(articleId).detachEvent("onmouseup",showCmt);
            $(this).text('开启划词评论');
        }
        else{
			if(!is_ie) getObj(articleId).addEventListener("mouseup", showCmt, true);
			else getObj(articleId).attachEvent('onmouseup',showCmt);
            $(this).text('关闭划词评论');
        }
    });

    function getPos(evt)
    {
        try
        {
            if(is_ie)
            {
                x_pos = window.event.clientX + document.documentElement.scrollLeft + document.body.scrollLeft;
                y_pos = window.event.clientY + document.documentElement.scrollTop + document.body.scrollTop;

            }
            else
            {
                x_pos = evt.clientX + window.scrollX;
                y_pos = evt.clientY + window.scrollY;
            }
       }
        catch(x){}
    }

    function showCmt(e)
    {
        if(getSel() == '') return;
        $('#float-cmt li[sig]').hide();
        getPos(e);
        x_pos += 8;
        y_pos += 16;
        cmt.style.left = x_pos + 'px';
        cmt.style.top = y_pos + 'px';
        cmt.style.display = 'inline';
    }

    function showClickCmt(e,sig)
    {
        getPos(e);
        x_pos += 8;
        y_pos += 20;
        cmt.style.left = x_pos + 'px';
        cmt.style.top = y_pos + 'px';

        cmt.style.display = 'inline';
        $('#float-cmt li[sig]').hide();

        $(cmt).prepend($('li[sig="'+sig+'"]').clone());
        //$('li[sig="'+sig+'"]').show();
        $('#float-cmt a:contains("回复")').hide();
    }

    function hideCmt()
    {
        cmt.style.display = 'none';
    }

    function keyHideCmt(e)
	{
		//alert(e.keyCode);
        if(e.keyCode == '27')
        {
           if(selectHighLight)
            {
                if(currentSigma!='') clearHighLight();
                selectHighLight = false;
            }
            hideCmt();
        }
    }

    function mouseHideCmt(e)
	{
		
        if(selectHighLight)
        {
            if(currentSigma!='') clearHighLight();
			selectHighLight = false;
        }
        
        hideCmt();
    }

    function clearHighLight()
	{
        var seg = currentSigma.split(',');
        var word = cnt.substr(seg[0],seg[1]-seg[0]);
        //$("#"+articleId).html($("#"+articleId).html().replace('<span class="highlight">'+word+'</span>',word));
		$('.highlight').each(function(i){
			
            if(typeof($(this).attr('sigma')) == 'undefined')
            {
                var txt = $(this).text();
				
                $(this).after(txt);
                $(this).remove();
            }
        });
        currentSigma = '';
    }

    function setEl(el, htmlCode) {
        if(!el || 'undefined' == typeof el) return;
        if (is_ie) {
            el.innerHTML = '<div style="display:none">for IE</div>' + htmlCode;
            el.removeChild(el.firstChild);
        }
        else {
            var el_next = el.nextSibling;
            var el_parent = el.parentNode;
            el_parent.removeChild(el);
            el.innerHTML = htmlCode;
            if (el_next) {
                el_parent.insertBefore(el, el_next)
            } else {
                el_parent.appendChild(el);
            }
        }
    }


    function getObj(id)
    {
        if (document.getElementById) return document.getElementById(id);
        else if (document.all) return document.all[id];
        else if (document.layers) return document.layers[id];
        else {return null;}
    }

    function getSel() {
        if(arguments[0])
        {

        }
        else
        {
            if (window.getSelection) {//FF
                var str = window.getSelection().getRangeAt(0);
                //console.log(str);
                if(str.toString()!='')
                {
                    //保存当前的Sigma
                    var startSig = cnt.indexOf(str);
                    var endSig = cnt.indexOf(str)+str.toString().length;

                    for(var i=0;i<sigma.length;i++)
                    {
                        var sig = sigma[i].split(",");
                        if(startSig<sig[0])
                        {
                            if(endSig>sig[0]) return '';
                        }
                        if(endSig>sig[1])
                        {
                            if(startSig<sig[1]) return '';
                        }
                    }

                    currentSigma = cnt.indexOf(str)+","+(cnt.indexOf(str)+str.toString().length);
                    var sp = document.createElement("span");
                    sp.className = 'highlight';
                    str.surroundContents(sp);
                    selectHighLight = true;
                }

            } else if (document.selection && document.selection.createRange) {
                var range = document.selection.createRange();
                var str = range.text;
                if(str!='')
				{
					currentSigma = cnt.indexOf(str)+","+(cnt.indexOf(str)+str.toString().length);
                    range.pasteHTML('<span class="highlight">'+range.text+'</span>');
					selectHighLight = true;
                }


            } else {
                var str = "";
            }
            return str;
        }


    }

    //获取对应id的纯文本内容
    var cnt = '';
    function getText()
    {
        //cnt = $("#"+articleId).text().replace(/(\s*)/g, "");
        cnt = $.trim($("#"+articleId).text());
    }

    //高亮关键字
    function highlightWord(word,sig) {
        $("#"+articleId).html($("#"+articleId).html().replace(word,'<span class="highlight" sigma="'+sig+'">'+word+'</span>'));
        
    }

    //点击高亮区域
    function addClickListener()
    {
        $(".highlight").click(function(evt){
            //$("li[sig='"+$(this).attr('sigma')+"']").show();
            showClickCmt(evt,$(this).attr('sigma'));
            currentSigma = $(this).attr('sigma');
            //alert($(this).attr('sigma'));
        });
    }


    getText();
    //高亮已有评论的内容
    for(var i=0;i<sigma.length;i++)
    {
        var seg = sigma[i].split(',');
        highlightWord(cnt.substr(seg[0],seg[1]-seg[0]),sigma[i]);
    }
    addClickListener();

    init();

    //表单ajax提交
    $("#cmtform").submit(function(){
        document.cookie = 'sigma='+currentSigma+';path=/';
        document.cookie = "postID=$postID"+";path=/";
        //$.post('<?php echo get_option('siteurl'); ?>/wp-comments-post.php',$("#cmtform").serializeArray(),function(data){onPosted(data)});
        //return false;
    });

    function onPosted(data)
    {
        alert(data);
    }

</SCRIPT>
EOT;
}

register_activation_hook(__FILE__,'db_install');
add_action('comment_post','add_sigma');
add_action('wp_head','add_jquery');
?>
